import os
import mimetypes
import sys

import wython

class ResourcesStencil:
	def setup(self, settings):
		self.settings = settings
		pass

	def execute(self, gate):
		root = self.settings['root'];
		# Normalize path
		relPath = os.path.normpath('/'.join(gate.env.args['extra']))
		if relPath.find('..') != -1:
			# Someone is trying to request something outside of the resources root
			raise wython.routing.RoutingException(403)
		# Make full path
		requestedFile = os.path.normpath(root + '/'+ relPath)
		if os.path.isfile(requestedFile):
			# Is file
			if not os.access(requestedFile, os.R_OK):
				# Server cannot read file
				raise wython.routing.RoutingException(403)
			# Set length
			gate.header('Content-Length', os.path.getsize(requestedFile))
			# Set MIME type
			mime = mimetypes.guess_type(requestedFile)
			if mime[0]:
				mime = mime[0]
			else:
				# Default to application/octet-streap
				mime = 'application/octet-stream'
			# Send headers
			gate.header('Content-type', mime)
			gate.sendHeaders()
			f = open(requestedFile, 'rb')
			# Stream file to OUT stream
			while 1:
				data = f.read(1024)
				if not data:
					break
				gate.env.out.write(data)
			return True
		elif os.path.isdir(requestedFile):
			# Is directory
			if (not ('listing' in self.settings)) or (not self.settings['listing']):
				# Directory listing prohibited
				raise wython.routing.RoutingException(403)
			else:
				# Send directory listing
				print requestedFile
				folders = [[x, 'dir'] for x in filter(os.path.isdir, [os.path.normpath(requestedFile + '/' + y) for y in os.listdir(requestedFile)])]
				files = [[x, 'file'] for x in filter(os.path.isfile, [os.path.normpath(requestedFile + '/' + y) for y in os.listdir(requestedFile)])]
				print '-----'
				gate.writen('<h1>Listing of %s</h1>' % requestedFile)
				gate.writen('<pre>')
				for path, entryType in folders + files:
					#print 'Item: %s' % item
					if entryType == 'dir':
						gate.writen('[ FOLDER ]  <a href="%s/">%s</a>' % (os.path.basename(path), os.path.basename(path)))
					else:
						gate.writen('[  FILE  ]  <a href="%s">%s</a>' % (os.path.basename(path), os.path.basename(path)))
				gate.writen('</pre>')
			return True
		else:
			# File doesn't exist
#			raise NotFoundException('Not found =/')
			# Continue routing
			return False
